package com.example.myapplication.chap05;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;

//【例5-4】 应用SharedPreferences保存联系电话
public class SharedActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText name, tel;
    private Button btn_Save, btn_Get;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_05_sp);
        name = (EditText) findViewById(R.id.name);
        tel = (EditText) findViewById(R.id.tel);
        btn_Save = (Button) findViewById(R.id.btn_Save);
        btn_Get = (Button) findViewById(R.id.btn_Get);
        btn_Save.setOnClickListener(this);
        btn_Get.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        SharedPreferences sp = this.getSharedPreferences("phoneBook", Context.MODE_PRIVATE);

        if (view.getId() == R.id.btn_Save) {

            String str1 = name.getText().toString();
            String str2 = tel.getText().toString();
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("name", str1);
            editor.putString("phone", str2);
            editor.commit();
            Log.i("保存", "成功！");


//            SQLiteDatabase sq =  openOrCreateDatabase("mydata",Context.MODE_PRIVATE,null);
//            String DATABASE_CREATE="CREATE  TABLE  IF  NOT  EXISTS　" + "book" + " (" +
//            "ID"  + "　INTEGER primary key autoincrement," +
//                    "title" + "　text not null, " +
//                    "content" + "　text not null)";
//            //sq.execSQL(DATABASE_CREATE);//创建数据表
//            Log.w("SQL",DATABASE_CREATE);
//            sq.close();
        } else if (view.getId() == R.id.btn_Get) {
            name.setText(sp.getString("name", "Null"));
            tel.setText(sp.getString("phone", "Null"));

        }
    }
}
